package net.lunjin.controller;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.lunjin.bean.Information;
import net.lunjin.bean.LookWant;
import net.lunjin.bean.News;
import net.lunjin.bean.Organizations;
import net.lunjin.bean.People;
import net.lunjin.bean.Remark;
import net.lunjin.service.BlackListService;
import net.lunjin.service.InformationService;
import net.lunjin.service.LookWantService;
import net.lunjin.service.NewsService;
import net.lunjin.service.OrganizationsService;
import net.lunjin.service.PeopleService;
import net.lunjin.service.RemarkService;
import net.lunjin.util.Constants;
import net.lunjin.util.ProjectUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import finaler.util.DateUtil;
import finaler.util.Page;
import finaler.util.PageList;

@Controller
@RequestMapping("company")
public class CompanyController {

	@Autowired
	private InformationService informationService;
	
	@Autowired
	private OrganizationsService organizationsService;

	@Autowired
	private RemarkService remarkService;

	@Autowired
	private PeopleService peopleService;

	@Autowired
	private NewsService newsService;

	@Autowired
	private LookWantService lookWantService;

	@Autowired
	private BlackListService blackListService;

	/**
	 * 首页
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping( value="/all/" )
	public String index(HttpServletRequest request) throws Exception {
		Page page = new Page(request);
		page.setRange(15);
		page.putParameter("searchkey", request.getParameter("searchkey"));
		page.putParameter("comin", request.getParameter("comin"));
		page.putParameter("iscom", request.getParameter("iscom"));
		page.putParameter("able", request.getParameter("able"));
		page.putParameter("combg", request.getParameter("combg"));
		page.putParameter("secu", request.getParameter("secu"));
		page.putParameter("speed", request.getParameter("speed"));
		page.putParameter("foruser", request.getParameter("foruser"));
		page.putParameter("network", request.getParameter("network"));
		page.putParameter("orgvip", request.getParameter("orgvip"));
		PageList organizationsList = organizationsService.getOrgList(page);//首页机构
		request.setAttribute("organizationsList", organizationsList);

		List<News> bbsNewsList = newsService.getBbsTopRecord(10);//10条交流新贴
		request.setAttribute("bbsNewsList", bbsNewsList);
		
		List<News> fmNewsList = newsService.getRandomRecord(0, 20);//随机20条负面新闻
		request.setAttribute("fmNewsList", fmNewsList);
		
		return "/company/companyList";
	}
	
	/**
	 * 推荐的交易平台
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping( value="/recommend.html" )
	public String recommend(HttpServletRequest request) throws Exception {
		
		List<News> bbsNewsList = newsService.getBbsTopRecord(10);//5条交流新贴
		request.setAttribute("bbsNewsList", bbsNewsList);

		List<News> fmNewsList = newsService.getRandomRecord(0, 10);//随机15条负面新闻
		request.setAttribute("fmNewsList", fmNewsList);
		
		Page page = new Page(request);
		page.setRange(50);
		PageList organizationsList = organizationsService.getRecommendOrgList(page);//推荐的交易平台
		request.setAttribute("organizationsList", organizationsList);
		request.setAttribute("recommend", "recommend");
		return "/company/companyList"; 
	}

	/**
	 * 评分高的平台
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping( value="/highscore.html" )
	public String highscore(HttpServletRequest request) throws Exception {
		List<News> bbsNewsList = newsService.getBbsTopRecord(10);//10条交流新贴
		request.setAttribute("bbsNewsList", bbsNewsList);

		List<News> fmNewsList = newsService.getRandomRecord(0, 10);//随机15条负面新闻
		request.setAttribute("fmNewsList", fmNewsList);
		
		Page page = new Page(request);
		page.setRange(50);
		PageList organizationsList = organizationsService.getHighscoreOrgList(page);//评分高的平台
		request.setAttribute("organizationsList", organizationsList);
		return "/company/companyList"; 
	}

	/**
	 * 评分低的平台
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping( value="/lowscore.html" )
	public String lowscore(HttpServletRequest request) throws Exception {
		List<News> bbsNewsList = newsService.getBbsTopRecord(10);//10条交流新贴
		request.setAttribute("bbsNewsList", bbsNewsList);

		List<News> fmNewsList = newsService.getRandomRecord(0, 30);//随机30条负面新闻
		request.setAttribute("fmNewsList", fmNewsList);
		
		Page page = new Page(request);
		page.setRange(50);
		PageList organizationsList = organizationsService.getLowscoreOrgList(page);//评分低的平台
		request.setAttribute("organizationsList", organizationsList);
		return "/company/companyList"; 
	}
	
	
	@RequestMapping( value="/{orgId}.html" )
	public String company(@PathVariable BigDecimal orgId,HttpServletRequest request) throws Exception {
		Organizations company = organizationsService.findByKey(orgId);//得到平台详细
		if(company==null){
			return "redirect:"+Constants.URL;
		}
		request.setAttribute("company", company);
		
		Organizations updCom = new Organizations();
		updCom.setId(orgId);
		updCom.setHit( company.getHit( ).add(new BigDecimal(1))  );//浏览数更新
		organizationsService.update( updCom );		
		
		List<Information> informationList  = informationService.getInformationList(orgId);//得到资讯信息
		request.setAttribute("informationList", informationList);

		Map<String, Object> coinMap = remarkService.getAvgFen(orgId);//平均分集
		request.setAttribute("coinMap", coinMap);
		
		Page page = new Page(request);
		page.setRange(50);//每页50个评论
		page.putParameter("orgId", orgId);
		PageList remarkList = remarkService.getRemarkList(page);//得到评论集
		request.setAttribute("remarkList", remarkList);
		
		int wantPeopleCount = peopleService.getCountWantPeople(orgId);
		request.setAttribute("wantPeopleCount", wantPeopleCount);
		
		List<People> top5WantPeopleList = peopleService.getTop5WantPeople(orgId);
		request.setAttribute("top5WantPeopleList", top5WantPeopleList);
		
		List<People> allProxyList = peopleService.getAllProxy(orgId);
		request.setAttribute("allProxyList", allProxyList);
		
		Page page2 = new Page(request);
		page2.setRange(20);
		page2.putParameter("newsType", 0);
		page2.putParameter("searchkey", company.getOrgshortname());
		PageList aboutNewsList = newsService.getNewsList(page2);//新闻查询
		request.setAttribute("aboutNewsList", aboutNewsList);
		
		int a = new Random().nextInt(10);
		int b = new Random().nextInt(10);
		int c = a  + b;
		request.setAttribute("ss", a+"+"+b);//评论验证码
		request.getSession().setAttribute("cc", c);
		
		String pic1 = company.getOrgvip().intValue()==1?"1":"0";
		String pic2 = company.getSecu().intValue()==1?"1":"0";
		String pic3 = company.getAble().intValue()==1?"1":"0";
		String pic4 = coinMap.get("avgzcoin")==null?"0":Integer.parseInt(coinMap.get("avgzcoin").toString())>70?"1":"0";
		String accrPic = pic1 + pic2 + pic3 + pic4 ;
		request.setAttribute("accrPic", accrPic);
		
		List<Organizations> randomComList = organizationsService.getRandomComList(40);
		request.setAttribute("randomComList", randomComList);
		
		return "/company/company";
	}

	@RequestMapping( value="/remark",method=RequestMethod.POST )
	public String remark(HttpServletRequest request,HttpServletResponse response) throws Exception {
		if(request.getSession().getAttribute("cc")==null ||
				!request.getSession().getAttribute("cc").toString().equals(request.getParameter("cc"))){//防外部提交
			response.setContentType("text/html; charset=utf-8");
			response.getWriter().print("<script>alert('验证码不正确!请重新输入!');window.history.go(-1);</script>");
			return null;
		}
		
		if(blackListService.isBlackList(request.getRemoteAddr())){//被列黑名单不能评
			response.setContentType("text/html; charset=utf-8");
			response.getWriter().print("<script>alert('您被列为本站不欢迎对象!操作已被禁止!');window.history.go(-1);</script>");
			return null;
		}
		Page page = new Page(request);
		page.setRange(1);
		page.putParameter("orgId", request.getParameter("orgId"));
		PageList remarkList = remarkService.getRemarkList(page);//得到评论集
		boolean firstRemark = remarkList.getTotal()==0?true:false;
		BigDecimal yCoin = new BigDecimal(request.getParameter("ycoin"));
		BigDecimal dCoin = new BigDecimal(request.getParameter("dcoin"));
		BigDecimal rCoin = new BigDecimal(request.getParameter("rcoin"));
		BigDecimal kCoin = new BigDecimal(request.getParameter("kcoin"));
		if(firstRemark){//如果第一次评论,就会把>80分的,变成60分
			yCoin = Integer.parseInt(request.getParameter("ycoin"))>=80?new BigDecimal(60):yCoin;
			dCoin = Integer.parseInt(request.getParameter("dcoin"))>=80?new BigDecimal(60):dCoin;
			rCoin = Integer.parseInt(request.getParameter("rcoin"))>=80?new BigDecimal(60):rCoin;
			kCoin = Integer.parseInt(request.getParameter("kcoin"))>=80?new BigDecimal(60):kCoin;
		}
		
		Remark remark = new Remark();
		remark.setRmcontent(request.getParameter("rmcontent").replaceAll("<", "＜").replaceAll("\n", "<br/>"));//内容
		remark.setAutoflag(new BigDecimal(0));//正常发
		remark.setOrgid(new BigDecimal(request.getParameter("orgId")));
		remark.setYcoin(yCoin);
		remark.setDcoin(dCoin);
		remark.setRcoin(rCoin);
		remark.setKcoin(kCoin);
		remark.setCreatetime(DateUtil.getCurrentDate("yyyy-MM-dd HH:mm:ss"));
		remark.setCreateuser(request.getRemoteAddr());
		remarkService.insert(remark);
		return "redirect:/company/"+request.getParameter("orgId")+".html#remarkDiv"; 
	}

	@RequestMapping( value="/people_{orgId}",method=RequestMethod.POST )
    @ResponseBody
	public Object people(@PathVariable BigDecimal orgId,HttpServletRequest request) throws Exception {
		String telipqq = request.getParameter("telipqq");
		String typeflag = request.getParameter("typeflag");
		People existPeople = peopleService.findPeople(orgId,telipqq,typeflag);//已经登记过
		if(existPeople!=null){
			return "ng";
		}
		People newPeople = new People();
		newPeople.setOrgid(orgId);
		newPeople.setTelipqq(telipqq);
		newPeople.setTypeflag(new BigDecimal(typeflag));
		newPeople.setCreatetime(DateUtil.getCurrentDate("yyyy-MM-dd"));
		peopleService.insert(newPeople);
		return "ok";
	}

	@RequestMapping( value="/addInformation_{orgId}",method=RequestMethod.POST )
    @ResponseBody
	public Object addinformation(@PathVariable BigDecimal orgId,HttpServletRequest request) throws Exception {
		Information information = new Information();
		information.setAuditFlag(new BigDecimal(0));
		information.setIfcontent(request.getParameter("ifcontent"));
		information.setOrgid(orgId);
		information.setCreatetime(DateUtil.getCurrentDate("yyyy-MM-dd HH:mm:ss"));
		informationService.insert(information);
		return "ok";
	}

	@RequestMapping( value="/want.html" )
	public String want(HttpServletRequest request) throws Exception {
		Page page = new Page(request);
		page.setRange(20);
		page.putParameter("companyId", request.getParameter("companyId"));
		PageList wantList = peopleService.getWantPeople(page);
		request.setAttribute("wantList", wantList);
		if(request.getParameter("companyId")!=null){
			Organizations company  = organizationsService.findByKey(new BigDecimal(request.getParameter("companyId")));
			request.setAttribute("company", company);
		}
		if(request.getParameter("password")!=null){
			LookWant lookWant  = lookWantService.find(new BigDecimal(request.getParameter("companyId")),request.getParameter("password").replaceAll(".*([';]+|(--)+).*", ""));
			request.setAttribute("lookWant", lookWant);
		}
		return "/company/want";
	}
	
	@RequestMapping( value="/add.html" )
	public String add(HttpServletRequest request) throws Exception {
		int a = new Random().nextInt(10);
		int b = new Random().nextInt(10);
		int c = a  + b;
		request.setAttribute("s", a+"+"+b);
		request.getSession().setAttribute("c", c);
		return "/company/add";
	}
	
	@RequestMapping( value="/save",method=RequestMethod.POST )
    @ResponseBody
	public void save(HttpServletRequest request,HttpServletResponse response) throws Exception {
		if(request.getSession().getAttribute("c")==null ||
				!request.getSession().getAttribute("c").toString().equals(request.getParameter("c"))){//防外部提交
			response.setContentType("text/html; charset=utf-8");
			response.getWriter().print("<script>alert('验证码不正确!请重新输入!');window.history.go(-1);</script>");
			return;
		}
		Organizations org = new Organizations();
		org.setOrgname(ProjectUtil.notNull(request.getParameter("orgname"),""));
		org.setOrgshortname(ProjectUtil.notNull(request.getParameter("orgshortname"),""));
		org.setOrgtel(ProjectUtil.notNull(request.getParameter("orgtel"),""));
		org.setOrgaddr(ProjectUtil.notNull(request.getParameter("orgaddr"),""));
		org.setWhencreate(ProjectUtil.notNull(request.getParameter("whencreate"),""));
		org.setWeb(ProjectUtil.notNull(request.getParameter("web"),""));

		org.setComin( new BigDecimal(request.getParameter("comin") ));
		org.setIscom( new BigDecimal(request.getParameter("iscom") ));
		org.setAble( new BigDecimal(request.getParameter("able") ));
		org.setCombg( new BigDecimal(request.getParameter("combg") ));
		org.setSecu( new BigDecimal(request.getParameter("secu") ));
		org.setSpeed( new BigDecimal(request.getParameter("speed") ));
		org.setForuser( new BigDecimal(request.getParameter("foruser") ));

		org.setOrgcontent(request.getParameter("orgcontent").replaceAll("\n", "<br/>"));
		org.setAuditFlag(new BigDecimal(0));//未审核
		organizationsService.insert(org);
		response.setContentType("text/html; charset=utf-8");
		response.getWriter().print("<script>alert('添加成功,请等待审核!');window.location='"+Constants.URL+"'</script>");
	}
	
	@RequestMapping( value="/{orgId}.js" )
	public void accr(@PathVariable BigDecimal orgId,HttpServletResponse response) throws Exception {
		Organizations company = organizationsService.findByKey(orgId);//得到平台详细
		if(company==null){
			response.getWriter().print("document.write('无该公司!徽章无法显示!');");
		}else{
			String pic1 = company.getOrgvip().intValue()==1?"1":"0";
			String pic2 = company.getSecu().intValue()==1?"1":"0";
			String pic3 = company.getAble().intValue()==1?"1":"0";
			
			Map<String, Object> coinMap = remarkService.getAvgFen(orgId);//平均分集
			String pic4 = coinMap.get("avgzcoin")==null?"0":Integer.parseInt(coinMap.get("avgzcoin").toString())>70?"1":"0";
			
			String pic = pic1 + pic2 + pic3 + pic4 ;
			response.getWriter().print("document.write('<a href=\""+Constants.URL+"/company/"+orgId+".html\" target=\"_blank\"><img src=\""+Constants.URL+"/images/accr/"+pic+".gif\" border=\"0\" alt=\""+company.getOrgname()+"认证徽章\" title=\""+company.getOrgname()+"认证徽章\" /></a>');");
		}
	}

	@RequestMapping( value="/allComForSeo/" )
	public String allCom(HttpServletRequest request) throws Exception {
		Page page = new Page(request);
		page.setRange(200);
		PageList organizationsList = organizationsService.getOrgList(page);//机构
		request.setAttribute("organizationsList", organizationsList);
		return "/company/allComForSeo";
	}

	@RequestMapping( value="/vip.html" )
	public String vip(HttpServletRequest request) throws Exception {
		return "/company/vip";
	}
}
